package com.woniuxy.core.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.core.mapper.ShopOrderItemMapper;
import com.woniuxy.core.mapper.ShopOrderMapper;
import com.woniuxy.core.service.ShopOrderService;
import com.woniuxy.entity.*;
import com.woniuxy.entity.DTO.ShopOrderDTO;
import com.woniuxy.enums.order.ShopOrderStatus;
import com.woniuxy.feign.AllContentApi;
import com.woniuxy.feign.AllUserApi;
import com.woniuxy.mq.message.OrderMessage;
import com.woniuxy.mq.message.PaymentSuccessMessage;
import com.woniuxy.util.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author hq
 * @Date 2025/7/14$ 12:05$
 * @Description 订单服务实现类
 **/
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class ShopOrderServiceImpl implements ShopOrderService {

    @Autowired
    private ShopOrderMapper shopOrderMapper;

    @Autowired
    private ShopOrderItemMapper shopOrderItemMapper;

    @Autowired
    private AllContentApi allContentApi;

    @Autowired
    private AllUserApi allUserApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 订单超时时间（秒）
    private static final long ORDER_TIMEOUT_SECONDS = 15 * 60;

    // Redis key前缀
    private static final String ORDER_STATUS_KEY_PREFIX = "order:status:";

    // 订单延迟队列配置
    private static final String ORDER_DELAY_EXCHANGE = "order.delay.exchange";
    private static final String ORDER_DELAY_ROUTING_KEY = "order.delay.routingKey";

    // 支付服务相关配置
    private static final String ORDER_CREATED_EXCHANGE = "order.created.exchange";
    private static final String ORDER_CREATED_ROUTING_KEY = "order.created";

    // 支付成功队列
    private static final String ORDER_PAY_SUCCESS_QUEUE = "order.pay.success.queue";

    /**
     * 条件分页查询订单
     */
    @Override
    public PageResult queryShopOrder(Integer pageNum, Integer pageSize, ShopOrder shopOrder) {
        PageHelper.startPage(pageNum, pageSize);
        List<ShopOrderDTO> list = shopOrderMapper.queryShopOrder(shopOrder);
        PageInfo info = new PageInfo<>(list);
        PageResult pageResult = new PageResult();
        pageResult.setTotal(info.getTotal());
        pageResult.setList(info.getList());
        pageResult.setPageNum(info.getPageNum());
        pageResult.setPageSize(info.getPageSize());
        return pageResult;
    }

    /**
     * 根据id查询订单
     */
    @Override
    public ShopOrderDTO getByOrderById(Integer orderId) {
        return shopOrderMapper.getById(orderId);
    }

    /**
     * 取消关闭订单
     * @param orderNumber
     */
    @Override
    public void closeOrder(String orderNumber) {
        // 查询订单
        ShopOrder order = shopOrderMapper.getByOrderByNumber(orderNumber);
        if (order == null || order.getStatus() != ShopOrderStatus.PENDING.getCode()) {
            return;
        }

        // 更新订单状态为已关闭
        shopOrderMapper.updateOrderStatusByNumber(orderNumber, ShopOrderStatus.CANCELED.getCode());

        // 释放优惠券（如果有）
        if (order.getCouponId() != null) {
            log.info("释放优惠券，优惠券ID：{}", order.getCouponId());
        }
        // 从Redis中删除订单状态
        redisTemplate.delete(getOrderStatusKey(order.getOrderNumber()));
    }
    /**
     * 支付成功，更新订单状态为已支付
     * @param orderId
     * @param status
     */
    @Override
    public void updateOrderStatus(Integer orderId, Integer status) {
        log.info("更新订单状态，订单ID：{}，状态：{}", orderId, 2);
        shopOrderMapper.updateOrderStatus(orderId);
    }

    /**
     * 根据订单编号查询订单
     * @param orderNumber
     * @return
     */
    @Override
    public ShopOrder getByOrderByNumber(String orderNumber) {
        return shopOrderMapper.getByOrderByNumber(orderNumber);
    }
    //提交评价根据shopOrder表里的id
    @Override
    public void addComment(Integer orderId,String commentInfo) {
         shopOrderMapper.addComment(orderId,commentInfo);

    }
    /**
     * 确认收货
     * @param orderId
     */
    @Override
    public void confirmOrder(Integer orderId) {
        shopOrderMapper.confirmOrder(orderId);
    }

    /**
     * 创建订单
     * @param shopOrder
     */
    @Override
    public ShopOrder createShopOrder(ShopOrder shopOrder) {
        // 1. 查询商品信息并校验
        AllShop item = allContentApi.getShopById(shopOrder.getItemId());
        log.info("查询商品信息：{}", item);

        // 校验商品状态
        Integer status = item.getStatus();
        if (status == null) {
            throw new RuntimeException("商品状态异常");
        }
        if (status != 1) {
            throw new RuntimeException("商品已下架");
        }

        // 2. 验证优惠券
        Coupon coupon = null;
        UserCoupon userCoupon = null;
        if (shopOrder.getCouponId() != null) {
            coupon = allUserApi.getCouponById(shopOrder.getCouponId());
            log.info("查询优惠券信息：{}", coupon);
            if (coupon == null) {
                throw new RuntimeException("优惠券不存在");
            }

            userCoupon = shopOrderMapper.getUserCouponById(coupon.getCouponId());
            log.info("查询用户关联优惠券信息：{}", userCoupon);
            if (userCoupon == null) {
                throw new RuntimeException("优惠券不存在");
            }
            if (userCoupon.getStatus() != 1) {
                throw new RuntimeException("优惠券已失效");
            }
         /*   if (coupon.getEndTime() == null) {
                throw new RuntimeException("优惠券未设置过期时间");
            }
            if (coupon.getEndTime().getTime() < System.currentTimeMillis()) {
                throw new RuntimeException("优惠券已过期");
            }
            if (item.getPrice().compareTo(coupon.getMinAmount()) < 0) {
                throw new RuntimeException("商品价格低于优惠券最低金额");
            }*/
        }

        // 3. 计算订单金额
        BigDecimal orderAmount = calculateTotalAmount(item, coupon, shopOrder.getPaymentMethod());

        // 4. 创建订单主表记录
        ShopOrder order = buildOrderMaster(shopOrder, item, coupon, orderAmount);
        shopOrderMapper.insert(order);

        // 5. 创建订单详情表记录
        ShopOrderItem orderItem = buildOrderItem(order.getOrderNumber(), order.getId(), item);
        shopOrderItemMapper.insert(orderItem);

        // 6. 锁定优惠券（如果有）
      /*  if (coupon != null) {
            try {
                log.info("正在锁定优惠券，couponId: {}", coupon.getCouponId());
                int rows = allUserApi.lockCoupon(coupon.getCouponId());
                if (rows != 1) {
                    throw new RuntimeException("优惠券已经被使用");
                }
                log.info("优惠券锁定成功");
            } catch (Exception e) {
                log.error("锁定优惠券失败: {}", e.getMessage(), e);
                // 可选：抛出异常、回滚事务 或 使用降级逻辑
                throw new RuntimeException("优惠券锁定失败，请稍后再试", e);
            }
        }*/
        // 7. 记录订单状态到Redis
        redisTemplate.opsForValue().set(
                getOrderStatusKey(order.getOrderNumber()),
                ShopOrderStatus.PENDING.name(),
                ORDER_TIMEOUT_SECONDS,
                TimeUnit.SECONDS
        );

        // 8. 发送延迟消息，用于订单超时关闭
        rabbitTemplate.convertAndSend(
                ORDER_DELAY_EXCHANGE,
                ORDER_DELAY_ROUTING_KEY,
                order.getOrderNumber(),
                message -> {
                    message.getMessageProperties().setExpiration(String.valueOf(ORDER_TIMEOUT_SECONDS * 1000));
                    return message;
                }
        );
        log.info("发送延迟消息，订单ID：{}，超时时间：{}秒", order.getOrderNumber(), ORDER_TIMEOUT_SECONDS);

        // 9. 发送订单创建消息给支付服务
        sendOrderCreatedMessage(order);

        // 10. 返回订单信息
        return order;
    }

    /**
     * 发送订单创建消息给支付服务
     */
    private void sendOrderCreatedMessage(ShopOrder order) {
        try {
            // 创建订单消息对象
            OrderMessage message = new OrderMessage();
            message.setOrderId(order.getId());
            message.setOrderNumber(order.getOrderNumber());
            message.setUserId(order.getUserId());
            message.setAmount(order.getTotalAmount());
            message.setExpireTime(order.getExpireTime());

            // 发送消息到MQ
            rabbitTemplate.convertAndSend(
                    ORDER_CREATED_EXCHANGE,
                    ORDER_CREATED_ROUTING_KEY,
                    message
            );

            log.info("发送订单创建消息，订单号：{}", order.getOrderNumber());
        } catch (Exception e) {
            log.error("发送订单创建消息失败，订单号：{}", order.getOrderNumber(), e);
        }
    }

    /**
     * 处理支付成功回调
     */
    @RabbitListener(queues = ORDER_PAY_SUCCESS_QUEUE)
    public void handlePaymentSuccess(PaymentSuccessMessage message) {
        log.info("收到支付成功消息: {}", message.getOrderNumber());

        try {
            // 1. 查询订单
            ShopOrder order = getByOrderByNumber(message.getOrderNumber());
            if (order == null) {
                log.error("订单不存在: {}", message.getOrderNumber());
                return;
            }

            // 2. 校验订单状态
            if (order.getStatus() != ShopOrderStatus.PENDING.getCode()) {
                log.warn("订单状态已变更，无需处理: {}", message.getOrderNumber());
                return;
            }

            // 3. 更新订单状态为已支付
            updateOrderStatus(order.getId(), ShopOrderStatus.PAID.getCode());

            // 4. 更新支付时间和交易ID
            updatePaymentInfo(
                    order.getOrderNumber(),
                    message.getPaymentTime()
            );

            // 5. 扣减商品库存
            log.info("开始扣减商品库存");

            // 6. 释放分布式锁（如果使用了）
            redisTemplate.delete(getOrderStatusKey(message.getOrderNumber()));

            log.info("订单支付处理完成: {}", message.getOrderNumber());

        } catch (Exception e) {
            log.error("处理支付成功消息失败", e);
            // 可以添加重试机制或发送到死信队列
        }
    }

    /**
     * 更新支付信息
     */
    public void updatePaymentInfo(String orderNumber, Date paymentTime) {
        shopOrderMapper.updatePaymentInfo(orderNumber, paymentTime);
    }

    /**
     * 获取订单状态Redis键
     */
    private String getOrderStatusKey(String orderNumber) {
        return ORDER_STATUS_KEY_PREFIX + orderNumber;
    }

    /**
     * 构建订单详情记录
     */
    private ShopOrderItem buildOrderItem(String orderNumber, Integer orderId, AllShop item) {
        ShopOrderItem orderItem = new ShopOrderItem();
        orderItem.setId(orderId);
        orderItem.setOrderNumber(orderNumber);
        orderItem.setItemId(item.getId());
        orderItem.setItemTitle(item.getTitle());
        orderItem.setItemPrice(item.getPrice());
        orderItem.setQuantity(1);
        orderItem.setCreateTime(new Date());
        return orderItem;
    }

    /**
     * 计算总金额
     */
    private BigDecimal calculateTotalAmount(AllShop item, Coupon coupon, Integer shippingMethod) {
        BigDecimal totalAmount = item.getPrice();

        // 计算运费
        BigDecimal shippingFee = getShippingFee(shippingMethod);
        totalAmount = totalAmount.add(shippingFee);

        // 计算优惠金额
        if (coupon != null && coupon.getAmount() != null) {
            totalAmount = totalAmount.subtract(coupon.getAmount());
        }

        return totalAmount;
    }


    /**
     * 根据运送方式计算运费
     */
    private BigDecimal getShippingFee(Integer shippingMethod) {
        if (shippingMethod == null) {
            return BigDecimal.valueOf(10); // 默认运费
        }
        if (shippingMethod == 2) { // 自提
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(10);
    }

    /**
     * 构建订单主表记录
     */
    private ShopOrder buildOrderMaster(ShopOrder shopOrder, AllShop item, Coupon coupon, BigDecimal totalAmount) {
        ShopOrder order = new ShopOrder();
        order.setOrderNumber(generateOrderNumber());
        order.setUserId(shopOrder.getUserId());
        order.setSellerId(item.getUserId());
        order.setItemId(item.getId());
        order.setTotalAmount(totalAmount);
        order.setCouponId(coupon != null ? coupon.getCouponId() : null);
        order.setCouponAmount(coupon != null ? coupon.getAmount() : BigDecimal.ZERO);
        order.setShippingMethod(shopOrder.getShippingMethod());
        order.setStatus(ShopOrderStatus.PENDING.getCode());
        //设置过期时间为15分钟
        order.setExpireTime(LocalDateTime.now().plusSeconds(ORDER_TIMEOUT_SECONDS));
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setPaymentMethod(shopOrder.getPaymentMethod());
        order.setPaymentTime(null);
        return order;
    }

    /**
     * 生成订单编号
     */
    private String generateOrderNumber() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        String randomSuffix = String.format("%06d", new Random().nextInt(1000000));
        return  timestamp + randomSuffix;
    }
}